package tu.java.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
	
	
	
	private String			from;
	private String			to;
	private String			subject;
	private String			text;
	private String			userPass;
	
	private final String	smtpHost;
	private final String	smtpPort;
	private final String	type;
	
	
	
	public SendMail(String from, String to, String subject, String text, String userPass, String smtpHost, String smtpPort, String type) {
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.text = text;
		this.userPass = userPass;
		this.smtpHost = smtpHost;
		this.smtpPort = smtpPort;
		this.type = type;
	}
	
	
	
	public boolean send() {
		
		boolean status = true;
		Properties props = new Properties();
		if (type.equalsIgnoreCase("TLS")) {
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", smtpPort);
		}
		else if (type.equalsIgnoreCase("SSL")) {
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.port", smtpPort);
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", smtpPort);
		}
		
		Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
			
			
			
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, userPass);
			}
		});
		Message simpleMessage = new MimeMessage(mailSession);
		
		InternetAddress fromAddress = null;
		InternetAddress toAddress = null;
		try {
			fromAddress = new InternetAddress(from);
			toAddress = new InternetAddress(to);
		}
		catch (AddressException e) {
			status = false;
			e.printStackTrace();
		}
		
		try {
			simpleMessage.setFrom(fromAddress);
			simpleMessage.setRecipient(RecipientType.TO, toAddress);
			simpleMessage.setSubject(subject);
			simpleMessage.setText(text);
			
			Transport.send(simpleMessage);
			System.out.println("Email sent successfully");
		}
		catch (MessagingException e) {
			status = false;
			e.printStackTrace();
		}
		return status;
	}
}